<template>
  <div class="app-container home">
    <!-- 页面标题 -->
    <div class="page-title">
      <h2 style="color: #00ff04">实时追踪 XDOG 市场表现、社区数据和价格走势</h2>
    </div>

    <!-- 实时价格信息 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card class="price-card" v-loading="loading.price">
          <template #header>
            <div class="card-header">
              <div class="card-header-content">
                <el-icon><Coin /></el-icon>
                <span>实时价格信息</span>
              </div>
              <el-button link type="primary" @click="refreshData">
                <el-icon><Refresh /></el-icon>
                刷新数据
              </el-button>
            </div>
          </template>
          <div class="price-info">
            <div class="price-item">
              <div class="price-label">
                <el-icon><PriceTag /></el-icon>
                <span>XDOG 价值</span>
              </div>
              <div class="price-value">${{ tokenData.price }}</div>
              <div class="price-change" :class="{ 'positive': parseFloat(tokenData.priceChange24H) >= 0 }">
                <el-icon v-if="parseFloat(tokenData.priceChange24H) >= 0"><Top /></el-icon>
                <el-icon v-else><Bottom /></el-icon>
                {{ parseFloat(tokenData.priceChange24H) >= 0 ? '+' : '' }}{{ tokenData.priceChange24H }}%
              </div>
            </div>
            <div class="price-item">
              <div class="price-label">
                <el-icon><TrendCharts /></el-icon>
                <span>24h 最高</span>
              </div>
              <div class="price-value">${{ tokenData.maxPrice }}</div>
            </div>
            <div class="price-item">
              <div class="price-label">
                <el-icon><DataAnalysis /></el-icon>
                <span>24h 最低</span>
              </div>
              <div class="price-value">${{ tokenData.minPrice }}</div>
            </div>
            <div class="price-item">
              <div class="price-label">
                <el-icon><Wallet /></el-icon>
                <span>24h 交易额</span>
              </div>
              <div class="price-value">${{ tokenData.volume24H }}</div>
            </div>
            <div class="price-item">
              <div class="price-label">
                <el-icon><PieChart /></el-icon>
                <span>当前市值</span>
              </div>
              <div class="price-value">${{ tokenData.marketCap }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 市场概览 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card class="overview-card" v-loading="loading.stats">
          <template #header>
            <div class="card-header">
              <div class="card-header-content">
                <el-icon><DataLine /></el-icon>
                <span>市场概览</span>
              </div>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">流通量</div>
                <div class="overview-value">{{ formatSupply(tokenData.circSupply) }}</div>
              </div>
            </el-col>
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">持有人数</div>
                <div class="overview-value">{{ tokenData.holders }}</div>
              </div>
            </el-col>
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">24h交易笔数</div>
                <div class="overview-value">{{ tokenData.txs24H }}</div>
              </div>
            </el-col>
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">池内流动性</div>
                <div class="overview-value">${{ formatLiquidity(tokenData.liquidity) }}</div>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="mt-3">
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">5分钟涨跌幅</div>
                <div class="overview-value" :class="{ 'positive': parseFloat(tokenData.priceChange5M) >= 0, 'negative': parseFloat(tokenData.priceChange5M) < 0 }">
                  {{ parseFloat(tokenData.priceChange5M) >= 0 ? '+' : '' }}{{ tokenData.priceChange5M }}%
                </div>
              </div>
            </el-col>
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">1小时涨跌幅</div>
                <div class="overview-value" :class="{ 'positive': parseFloat(tokenData.priceChange1H) >= 0, 'negative': parseFloat(tokenData.priceChange1H) < 0 }">
                  {{ parseFloat(tokenData.priceChange1H) >= 0 ? '+' : '' }}{{ tokenData.priceChange1H }}%
                </div>
              </div>
            </el-col>
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">4小时涨跌幅</div>
                <div class="overview-value" :class="{ 'positive': parseFloat(tokenData.priceChange4H) >= 0, 'negative': parseFloat(tokenData.priceChange4H) < 0 }">
                  {{ parseFloat(tokenData.priceChange4H) >= 0 ? '+' : '' }}{{ tokenData.priceChange4H }}%
                </div>
              </div>
            </el-col>
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">24小时涨跌幅</div>
                <div class="overview-value" :class="{ 'positive': parseFloat(tokenData.priceChange24H) >= 0, 'negative': parseFloat(tokenData.priceChange24H) < 0 }">
                  {{ parseFloat(tokenData.priceChange24H) >= 0 ? '+' : '' }}{{ tokenData.priceChange24H }}%
                </div>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="mt-3">
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">5分钟交易量</div>
                <div class="overview-value">${{ formatVolume(tokenData.volume5M) }}</div>
              </div>
            </el-col>
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">1小时交易量</div>
                <div class="overview-value">${{ formatVolume(tokenData.volume1H) }}</div>
              </div>
            </el-col>
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">4小时交易量</div>
                <div class="overview-value">${{ formatVolume(tokenData.volume4H) }}</div>
              </div>
            </el-col>
            <el-col :span="24" :md="6">
              <div class="overview-item">
                <div class="overview-label">24小时交易量</div>
                <div class="overview-value">${{ formatVolume(tokenData.volume24H) }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 核心指标展示 -->
    <el-row :gutter="24" class="mt-4">
      <el-col :span="24" :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" v-loading="loading.stats">
          <div class="stat-item">
            <el-icon class="stat-icon"><ChatDotRound /></el-icon>
            <div class="stat-label">推特讨论值</div>
            <div class="stat-value">{{ communityStats.twitterMentions }}</div>
            <div class="stat-change" :class="{ 'positive': communityStats.twitterMentionsChange >= 0 }">
              <el-icon v-if="communityStats.twitterMentionsChange >= 0"><Top /></el-icon>
              <el-icon v-else><Bottom /></el-icon>
              {{ communityStats.twitterMentionsChange >= 0 ? '+' : '' }}{{ communityStats.twitterMentionsChange }}%
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" v-loading="loading.stats">
          <div class="stat-item">
            <el-icon class="stat-icon"><UserFilled /></el-icon>
            <div class="stat-label">社区人数</div>
            <div class="stat-value">{{ communityStats.telegramMembers }}</div>
            <div class="stat-change" :class="{ 'positive': communityStats.telegramMembersChange >= 0 }">
              <el-icon v-if="communityStats.telegramMembersChange >= 0"><Top /></el-icon>
              <el-icon v-else><Bottom /></el-icon>
              {{ communityStats.telegramMembersChange >= 0 ? '+' : '' }}{{ communityStats.telegramMembersChange }}%
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" v-loading="loading.stats">
          <div class="stat-item">
            <el-icon class="stat-icon"><Avatar /></el-icon>
            <div class="stat-label">今日新增人数</div>
            <div class="stat-value">{{ communityStats.todayNewMembers }}</div>
            <div class="stat-change" :class="{ 'positive': communityStats.todayNewMembersChange >= 0 }">
              <el-icon v-if="communityStats.todayNewMembersChange >= 0"><Top /></el-icon>
              <el-icon v-else><Bottom /></el-icon>
              {{ communityStats.todayNewMembersChange >= 0 ? '+' : '' }}{{ communityStats.todayNewMembersChange }}%
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" v-loading="loading.stats">
          <div class="stat-item">
            <el-icon class="stat-icon"><Coin /></el-icon>
            <div class="stat-label">维稳基金余额</div>
            <div class="stat-value">{{ communityStats.stabilityFundBalance }}</div>
            <div class="stat-change">XDOG</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24" :xs="24" :sm="24" :md="12">
        <el-card v-loading="loading.charts">
          <template #header>
            <div class="card-header">
              <div class="card-header-content">
                <el-icon><TrendCharts /></el-icon>
                <span>XDOG价格走势</span>
              </div>
<!--              <el-button link type="primary" @click="refreshCharts">
                <el-icon><Refresh /></el-icon>
                刷新图表
              </el-button>-->
            </div>
          </template>
          <ChartContainer :options="xdogChartOptions" height="400px" />
        </el-card>
      </el-col>

      <el-col :span="24" :xs="24" :sm="24" :md="12">
        <el-card v-loading="loading.charts">
          <template #header>
            <div class="card-header">
              <div class="card-header-content">
                <el-icon><TrendCharts /></el-icon>
                <span>OKX价格走势</span>
              </div>
<!--              <el-button link type="primary" @click="refreshCharts">
                <el-icon><Refresh /></el-icon>
                刷新图表
              </el-button>-->
            </div>
          </template>
          <ChartContainer :options="okxChartOptions" height="400px" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 社区数据 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24" :xs="24" :sm="24" :md="12">
        <el-card v-loading="loading.charts">
          <template #header>
            <div class="card-header">
              <div class="card-header-content">
                <el-icon><ChatLineRound /></el-icon>
                <span>Telegram社区增长</span>
              </div>
            </div>
          </template>
          <ChartContainer :options="telegramChartOptions" height="300px" />
        </el-card>
      </el-col>

      <el-col :span="24" :xs="24" :sm="24" :md="12">
        <el-card v-loading="loading.charts">
          <template #header>
            <div class="card-header">
              <div class="card-header-content">
                <el-icon><ChatLineSquare /></el-icon>
                <span>Twitter讨论热度</span>
              </div>
            </div>
          </template>
          <ChartContainer :options="twitterChartOptions" height="300px" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 社区基金地址 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card class="fund-address-card">
          <template #header>
            <div class="card-header">
              <div class="card-header-content">
                <el-icon><Wallet /></el-icon>
                <span>社区基金地址</span>
              </div>
            </div>
          </template>
          <div class="fund-address-content">
            <div class="address-info">
              <div class="address-label">基金地址:</div>
              <div class="address-value">0xb59acba5a6a306658f92b59313e684186b2a403d</div>
              <el-button type="primary" link @click="copyAddress">
                <el-icon><CopyDocument /></el-icon>
                复制地址
              </el-button>
            </div>
            <el-row :gutter="20" class="mt-3">
              <el-col :span="8">
                <div class="fund-stat-item">
                  <div class="fund-stat-label">基金数量</div>
                  <div class="fund-stat-value">500,000 XDOG</div>
                  <div class="fund-stat-change positive">+2.5%</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="fund-stat-item">
                  <div class="fund-stat-label">24h变化</div>
                  <div class="fund-stat-value">+12,500 XDOG</div>
                  <div class="fund-stat-change positive">+2.5%</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="fund-stat-item">
                  <div class="fund-stat-label">更新时间</div>
                  <div class="fund-stat-value">2025-10-22 14:30</div>
                </div>
              </el-col>
            </el-row>

            <!-- 收支明细 -->
            <div class="fund-details">
              <div class="details-header" @click="toggleFundDetails">
                <span>收支明细</span>
                <el-icon :class="{ 'expanded': fundDetailsExpanded }">
                  <ArrowDown />
                </el-icon>
              </div>

              <div v-show="fundDetailsExpanded" class="details-content">
                <el-table :data="fundTransactions" style="width: 100%" size="small">
                  <el-table-column prop="date" label="日期" width="120" />
                  <el-table-column prop="type" label="类型" width="80">
                    <template #default="scope">
                      <el-tag :type="scope.row.type === '收入' ? 'success' : 'danger'">
                        {{ scope.row.type }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="amount" label="金额(XDOG)" width="120" align="right" />
                  <el-table-column prop="balance" label="余额(XDOG)" align="right" />
                  <el-table-column prop="description" label="说明" />
                </el-table>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 项目链接 -->
    <div class="project-links">
      <p>探索更多 XDOG 相关资源</p>
      <div class="project-links-container">
        <el-button type="primary" plain @click="goTarget('https://www.okx.com/')">
          <el-icon><Link /></el-icon>
          OKX官网
        </el-button>
        <el-button type="primary" plain @click="goTarget('https://twitter.com/XDogeChain')">
          <el-icon><Link /></el-icon>
          Twitter
        </el-button>
        <el-button type="primary" plain @click="goTarget('https://t.me/XDogeChain')">
          <el-icon><Link /></el-icon>
          Telegram
        </el-button>
        <el-button type="primary" plain @click="goTarget('https://explorer.xdoge.org/')">
          <el-icon><Link /></el-icon>
          区块浏览器
        </el-button>
      </div>
    </div>

    <!-- Twitter热门推文 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card class="twitter-card">
          <template #header>
            <div class="card-header">
              <div class="card-header-content">
                <el-icon><ChatDotRound /></el-icon>
                <span>社区热门推文</span>
              </div>
            </div>
          </template>
          <div class="twitter-content">
            <el-row :gutter="20">
              <el-col :span="24" :md="12" v-for="(tweet, index) in twitterData" :key="index" class="mb-3">
                <div class="tweet-item" @click="openTweet(tweet.url)">
                  <div class="tweet-header">
                    <img :src="tweet.user.profile_image_url_https" :alt="tweet.user.name" class="user-avatar">
                    <div class="user-info">
                      <div class="user-name">{{ tweet.user.name }}</div>
                      <div class="user-screen-name">@{{ tweet.user.screen_name }}</div>
                    </div>
                  </div>
                  <div class="tweet-text" v-html="formatTweetText(tweet.full_text)" :class="{ 'tweet-text-expanded': expandedTweets[index] }"></div>
                  <div class="tweet-expand" v-if="shouldShowExpandButton(tweet.full_text, index)" @click="toggleTweetExpand(index, $event)">
                    {{ expandedTweets[index] ? '收起' : '展开' }}
                    <el-icon>
                      <ArrowDown v-if="!expandedTweets[index]" />
                      <ArrowUp v-else />
                    </el-icon>
                  </div>
                  <div class="tweet-stats">
                    <span class="stat-item">
                      <el-icon><ChatDotRound /></el-icon>
                      {{ formatNumber(tweet.retweet_count) }}
                    </span>
                    <span class="stat-item">
                      <el-icon><Star /></el-icon>
                      {{ formatNumber(tweet.favorite_count) }}
                    </span>
                    <span class="stat-item">
                      <el-icon><View /></el-icon>
                      {{ formatNumber(tweet.views.count) }}
                    </span>
                    <span v-if="tweet.reply_count" class="stat-item">
                      <el-icon><ChatLineRound /></el-icon>
                      {{ formatNumber(tweet.reply_count) }}
                    </span>
                  </div>
                  <div class="tweet-date">
                    {{ formatTweetDate(tweet.created_at) }}
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Twitter用户推荐 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card class="twitter-users-card">
          <template #header>
            <div class="card-header">
              <div class="card-header-content">
                <el-icon><User /></el-icon>
                <span>推荐关注</span>
              </div>
            </div>
          </template>
          <div class="twitter-users-content">
            <el-row :gutter="20">
              <el-col :span="12" :md="4" v-for="(user, index) in twitterUsers" :key="index" class="mb-3">
                <div class="user-item" @click="openUser(user.screen_name)">
                  <img :src="user.profile_image_url_https" :alt="user.name" class="user-avatar-large">
                  <div class="user-name-large">{{ user.name }}</div>
                  <div class="user-screen-name-large">@{{ user.screen_name }}</div>
                  <div class="user-followers">
                    <el-icon><User /></el-icon>
                    {{ formatNumber(user.followers_count) }} 关注者
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import * as echarts from 'echarts'
import {
  Refresh, Coin, PriceTag, Top, Bottom, TrendCharts,
  Wallet, PieChart, DataLine, Money, User, ChatDotRound,
  UserFilled, Avatar, ChatLineRound, ChatLineSquare,
  CopyDocument, Link, Document, ArrowDown, ArrowUp, Star, View
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import ChartContainer from '@/components/Xdog/ChartContainer.vue'
import { getTokenPriceInfo, getTokenBasicInfo } from '@/api/web3/market'
import { searchTweets, getCachedTweets, getRecommendedUsers } from '@/api/web3/twitter'

// 响应式数据
const loading = ref({
  price: false,
  stats: false,
  charts: false
})

const fundDetailsExpanded = ref(false)

// 推文展开状态
const expandedTweets = ref({})

// Twitter数据
const twitterData = ref([])

// Twitter推荐用户
const twitterUsers = ref([])

const fundTransactions = ref([
  { date: '2025-10-22', type: '支出', amount: '50,000', balance: '500,000', description: '市场推广费用' },
  { date: '2025-10-20', type: '收入', amount: '12,500', balance: '550,000', description: '社区捐赠' },
  { date: '2025-10-18', type: '支出', amount: '30,000', balance: '537,500', description: '技术开发支出' },
  { date: '2025-10-15', type: '收入', amount: '25,000', balance: '567,500', description: '合作伙伴赞助' },
  { date: '2025-10-10', type: '支出', amount: '20,000', balance: '542,500', description: '社区活动费用' },
  { date: '2025-10-05', type: '收入', amount: '15,000', balance: '562,500', description: '空投活动资金' }
])

// 社区统计数据（模拟数据）
const communityStats = ref({
  twitterMentions: '2,847',
  twitterMentionsChange: 5.2,
  telegramMembers: '18,542',
  telegramMembersChange: 1.8,
  todayNewMembers: '342',
  todayNewMembersChange: 12.5,
  stabilityFundBalance: '500,000'
})

const toggleFundDetails = () => {
  fundDetailsExpanded.value = !fundDetailsExpanded.value
}

// 切换推文展开状态
const toggleTweetExpand = (index, event) => {
  // 阻止事件冒泡，避免触发卡片的点击跳转
  event.stopPropagation()
  expandedTweets.value[index] = !expandedTweets.value[index]
}

// 判断是否应该显示展开按钮
const shouldShowExpandButton = (text) => {
  if (!text) return false

  // 字符数超过一定长度
  if (text.length > 280) return true

  // 包含换行符较多
  if (text.split('\n').length > 5) return true

  // 包含多个链接
  const linkCount = (text.match(/https?:\/\/[^\s]+/g) || []).length
  if (linkCount > 2) return true

  return false
}

// 代币完整数据
const tokenData = ref({
  chainIndex: '196',
  tokenContractAddress: '0x0cc24c51bf89c00c5affbfcf5e856c25ecbdb48e',
  time: '',
  price: '0',
  marketCap: '0',
  priceChange5M: '0',
  priceChange1H: '0',
  priceChange4H: '0',
  priceChange24H: '0',
  volume5M: '0',
  volume1H: '0',
  volume4H: '0',
  volume24H: '0',
  txs5M: '0',
  txs1H: '0',
  txs4H: '0',
  txs24H: '0',
  maxPrice: '0',
  tradeNum: '0',
  minPrice: '0',
  circSupply: '0',
  liquidity: '0',
  holders: '0'
})

// 格式化推文文本
const formatTweetText = (text) => {
  // 简单处理链接和提及
  return text
    .replace(/https?:\/\/[^\s]+/g, '<a href="$&" target="_blank" style="color: #1da1f2;">$&</a>')
    .replace(/@(\w+)/g, '<span style="color: #1da1f2;">@$1</span>')
    .replace(/#\w+/g, '<span style="color: #1da1f2;">$&</span>')
    .replace(/\n/g, '<br>')
}

// 格式化数字
const formatNumber = (num) => {
  if (typeof num === 'string') {
    num = parseInt(num)
  }
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num
}

// 格式化日期
const formatTweetDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

// 图表配置
const xdogChartOptions = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['XDOG价格']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['10-16', '10-17', '10-18', '10-19', '10-20', '10-21', '10-22']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: 'XDOG价格',
      type: 'line',
      smooth: true,
      data: [0.0102, 0.0105, 0.0108, 0.0112, 0.0110, 0.0109, 0.01094],
      itemStyle: {
        color: '#409eff'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
          { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
        ])
      }
    }
  ]
}))

const okxChartOptions = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['OKB价格']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['10-16', '10-17', '10-18', '10-19', '10-20', '10-21', '10-22']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: 'OKB价格',
      type: 'line',
      smooth: true,
      data: [52.1, 52.8, 53.2, 52.9, 53.5, 53.8, 54.2],
      itemStyle: {
        color: '#67c23a'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(103, 194, 58, 0.5)' },
          { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
        ])
      }
    }
  ]
}))

const telegramChartOptions = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['社区人数']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['10月15日', '10月16日', '10月17日', '10月18日', '10月19日', '10月20日', '10月21日', '10月22日']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '社区人数',
      type: 'bar',
      data: [17500, 17800, 18000, 18200, 18350, 18500, 18600, 18542],
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#409eff' },
          { offset: 1, color: '#00f2fe' }
        ])
      }
    }
  ]
}))

const twitterChartOptions = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['讨论热度']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['10月15日', '10月16日', '10月17日', '10月18日', '10月19日', '10月20日', '10月21日', '10月22日']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '讨论热度',
      type: 'line',
      smooth: true,
      data: [2100, 2350, 2600, 2780, 2900, 3000, 2850, 2847],
      itemStyle: {
        color: '#409eff'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
          { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
        ])
      }
    }
  ]
}))

// 刷新数据
const refreshData = () => {
  loading.value.price = true
  loading.value.stats = true

  // 调用后端API获取实时价格信息
  const requestData = [{
    chainIndex: '196', // 根据实际返回数据，使用正确的链标识
    tokenContractAddress: '0x0cc24c51bf89c00c5affbfcf5e856c25ecbdb48e' // XDOG合约地址
  }]

  // 并行调用两个接口获取完整数据
  Promise.all([
    getTokenPriceInfo(requestData),
    getTokenBasicInfo(requestData)
  ]).then(([priceResponse, basicResponse]) => {
    let hasData = false;

    // 处理价格信息
    if (priceResponse.code === 200 && priceResponse.data && priceResponse.data.data && priceResponse.data.data.length > 0) {
      const priceData = priceResponse.data.data[0];

      // 更新价格相关信息，确保价格保留5位小数
      tokenData.value.price = priceData.price ? parseFloat(priceData.price).toFixed(5) : tokenData.value.price;
      tokenData.value.priceChange24H = priceData.priceChange24H || tokenData.value.priceChange24H;
      tokenData.value.maxPrice = priceData.maxPrice ? parseFloat(priceData.maxPrice).toFixed(5) : tokenData.value.maxPrice;
      tokenData.value.minPrice = priceData.minPrice ? parseFloat(priceData.minPrice).toFixed(5) : tokenData.value.minPrice;
      tokenData.value.volume24H = priceData.volume24H || tokenData.value.volume24H;
      tokenData.value.marketCap = priceData.marketCap || tokenData.value.marketCap;
      tokenData.value.volume5M = priceData.volume5M || tokenData.value.volume5M;
      tokenData.value.volume1H = priceData.volume1H || tokenData.value.volume1H;
      tokenData.value.volume4H = priceData.volume4H || tokenData.value.volume4H;
      tokenData.value.txs5M = priceData.txs5M || tokenData.value.txs5M;
      tokenData.value.txs1H = priceData.txs1H || tokenData.value.txs1H;
      tokenData.value.txs4H = priceData.txs4H || tokenData.value.txs4H;
      tokenData.value.txs24H = priceData.txs24H || tokenData.value.txs24H;
      tokenData.value.priceChange5M = priceData.priceChange5M || tokenData.value.priceChange5M;
      tokenData.value.priceChange1H = priceData.priceChange1H || tokenData.value.priceChange1H;
      tokenData.value.priceChange4H = priceData.priceChange4H || tokenData.value.priceChange4H;

      hasData = true;
    }

    // 处理基础信息
    if (basicResponse.code === 200 && basicResponse.data && basicResponse.data.data && basicResponse.data.data.length > 0) {
      const basicData = basicResponse.data.data[0];

      // 更新基础信息
      tokenData.value.chainIndex = basicData.chainIndex || tokenData.value.chainIndex;
      tokenData.value.tokenContractAddress = basicData.tokenContractAddress || tokenData.value.tokenContractAddress;
      tokenData.value.time = basicData.time || tokenData.value.time;
      tokenData.value.tradeNum = basicData.tradeNum || tokenData.value.tradeNum;
      tokenData.value.circSupply = basicData.circSupply || tokenData.value.circSupply;
      tokenData.value.liquidity = basicData.liquidity || tokenData.value.liquidity;
      tokenData.value.holders = basicData.holders || tokenData.value.holders;

      hasData = true;
    }

    if (hasData) {
      ElMessage.success('数据已更新');
    } else {
      ElMessage.warning('无法获取实时数据，使用模拟数据');
    }
  }).catch(error => {
    console.error('获取数据失败:', error);
    ElMessage.error('获取实时数据失败，使用模拟数据');
  }).finally(() => {
    loading.value.price = false;
    loading.value.stats = false;
  });
}

// 获取Twitter数据
const fetchTwitterData = async () => {
  try {
    loading.value.charts = true
    // 直接从缓存获取数据，不回退到API获取
    const response = await getCachedTweets({ keyword: 'xdog' })

    // 只有当返回的数据不为空时才处理
    if (response.code === 200 && response.data) {
      // 处理统一格式的Twitter数据
      if (response.data.tweets && response.data.tweets.length > 0) {
        twitterData.value = response.data.tweets.map(tweet => {
          return {
            full_text: tweet.text,
            favorite_count: tweet.likeCount || 0,
            retweet_count: tweet.retweetCount || 0,
            reply_count: tweet.replyCount || 0,
            views: { count: tweet.viewCount || 0 },
            created_at: tweet.createdAt,
            user: {
              name: tweet.user?.name || '',
              screen_name: tweet.user?.screenName || '',
              profile_image_url_https: tweet.user?.localAvatarPath || ''
            },
            url: `https://twitter.com/${tweet.user?.screenName || 'twitter'}/status/${tweet.id}`
          };
        });
      }
    }
  } catch (error) {
    console.error('获取Twitter数据失败:', error);
    ElMessage.error('获取Twitter数据失败');
  } finally {
    loading.value.charts = false;
  }
};

// 获取推荐关注的Twitter用户
const fetchRecommendedUsers = async () => {
  try {
    const response = await getRecommendedUsers();
    if (response.code === 200 && response.data) {
      twitterUsers.value = response.data.map(user => {
        return {
          name: user.name,
          screen_name: user.screenName,
          profile_image_url_https: user.localAvatarPath,
          followers_count: user.followersCount
        };
      });
    }
  } catch (error) {
    console.error('获取推荐用户失败:', error);
    ElMessage.error('获取推荐用户失败');
  }
};

// 使用模拟数据更新（当API调用失败时的备选方案）
// 格式化交易量为整数
const formatVolume = (volume) => {
  if (!volume) return '0';
  // 移除逗号并转换为浮点数
  const num = parseFloat(volume.toString().replace(/,/g, ''));
  // 返回整数部分
  return Math.floor(num).toLocaleString();
};

// 格式化流通量
const formatSupply = (supply) => {
  if (!supply) return '0';
  // 移除逗号并转换为浮点数
  const num = parseFloat(supply.toString().replace(/,/g, ''));
  // 根据规范，整数不显示小数点，有小数部分最多保留1位小数
  if (Math.floor(num) === num) {
    return Math.floor(num).toLocaleString();
  } else {
    return num.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 1 });
  }
};

// 格式化流动性（财务类数值保留两位小数）
const formatLiquidity = (liquidity) => {
  if (!liquidity) return '0.00';
  // 移除逗号并转换为浮点数
  const num = parseFloat(liquidity.toString().replace(/,/g, ''));
  // 财务类数值保留两位小数
  return num.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

// 刷新图表
const refreshCharts = () => {
  loading.value.charts = true

  setTimeout(() => {
    loading.value.charts = false
    ElMessage.success('图表已更新')
  }, 1000)
}

// 复制地址
const copyAddress = () => {
  navigator.clipboard.writeText('0xb59acba5a6a306658f92b59313e684186b2a403d')
    .then(() => {
      ElMessage.success('地址已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败:', err)
      ElMessage.error('复制失败，请手动复制')
    })
}

// 打开推文链接
const openTweet = (url: string) => {
  window.open(url, '_blank')
}

// 打开用户主页
const openUser = (screenName: string) => {
  window.open(`https://x.com/${screenName}`, '_blank')
}

// 打开外部链接
const goTarget = (url: string) => {
  window.open(url, '_blank')
}

onMounted(() => {
  // 初始化时获取数据
  refreshData();
  fetchTwitterData();
  fetchRecommendedUsers();
})
</script>

<style scoped>
.app-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.home {
  padding: 0;
}

/* 标题样式 */
.page-title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.page-title h1 {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 10px;
  background: linear-gradient(90deg, #409eff, #00f2fe);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.page-title p {
  font-size: 1.1rem;
  color: #606266;
  max-width: 600px;
  margin: 0 auto;
  line-height: 1.6;
}

/* 卡片样式优化 */
.el-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

/* 特殊卡片样式 */
.fund-address-card, .project-links {
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.fund-address-card:hover, .project-links:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f2f5;
  background: linear-gradient(90deg, #f8f9fa, #ffffff);
}

.card-header-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.2rem;
  font-weight: 600;
  color: #303133;
}

/* 价格卡片样式 */
.price-card {
  background: rgba(255, 255, 255, 0.95);
  color: #303133;
}

.price-card .card-header {
  background: linear-gradient(90deg, #f8f9fa, #ffffff);
  border-bottom: 1px solid #f0f2f5;
  color: #303133;
}

.price-card .card-header-content {
  color: #303133;
  font-weight: 600;
}

.price-info {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  padding: 20px 0;
  gap: 10px;
}

.price-item {
  text-align: center;
  padding: 20px 10px;
  border-right: 1px solid #f0f2f5;
  flex: 1;
  transition: all 0.3s ease;
}

.price-item:hover {
  transform: translateY(-5px);
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.price-card .el-col:last-child .price-item {
  border-right: none;
}

.price-label {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.price-value {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 5px;
}

.price-change {
  font-size: 14px;
  font-weight: 600;
}

.price-change.positive {
  color: #67c23a;
}

.price-change:not(.positive) {
  color: #f56c6c;
}

/* 概览卡片样式 */
.overview-card .overview-item {
  text-align: center;
  padding: 15px 10px;
  border-right: 1px solid #f0f2f5;
  min-height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  transition: all 0.3s ease;
}

.overview-card .overview-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background-color: #f8f9fa;
}

.overview-card .el-col:last-child .overview-item {
  border-right: none;
}

.overview-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.overview-value {
  font-size: 18px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 5px;
}

.overview-value.positive {
  color: #67c23a;
}

.overview-value.negative {
  color: #f56c6c;
}

.overview-subvalue {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.overview-change {
  font-size: 14px;
  font-weight: 600;
}

.overview-change.positive {
  color: #67c23a;
}

.overview-change.negative {
  color: #f56c6c;
}

/* 统计卡片样式 */
.stat-card {
  height: 140px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  background: linear-gradient(135deg, #409eff 0%, #00f2fe 100%);
  color: white;
  border-radius: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.stat-icon {
  font-size: 24px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.stat-value {
  font-size: 20px;
  font-weight: 700;
}

.stat-change {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3px;
  font-size: 12px;
  font-weight: 600;
  padding: 2px 6px;
  border-radius: 20px;
  display: inline-flex;
}

.stat-change.positive {
  background: rgba(255, 255, 255, 0.3);
}

.stat-change:not(.positive) {
  background: rgba(0, 0, 0, 0.1);
}

/* 基金地址卡片样式 */
.fund-address-card .address-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  background: linear-gradient(90deg, #f8f9fa, #ffffff);
  border-radius: 8px;
  margin-bottom: 20px;
}

.fund-details {
  margin-top: 20px;
  border-top: 1px solid #f0f2f5;
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  cursor: pointer;
  font-weight: 600;
  color: #303133;
  user-select: none;
}

.details-header:hover {
  background-color: #f8f9fa;
}

.details-header .el-icon {
  transition: transform 0.3s ease;
}

.details-header .el-icon.expanded {
  transform: rotate(180deg);
}

.details-content {
  padding: 10px 20px 20px;
}

.address-label {
  font-weight: 600;
  margin-right: 15px;
  color: #303133;
}

.address-value {
  flex: 1;
  font-family: 'Courier New', monospace;
  word-break: break-all;
  margin: 0 15px;
  font-size: 16px;
  color: #409eff;
  font-weight: 500;
}

.fund-stat-item {
  text-align: center;
  padding: 15px 0;
}

.fund-stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.fund-stat-value {
  font-size: 18px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 5px;
}

.fund-stat-change {
  font-size: 14px;
  font-weight: 600;
}

.fund-stat-change.positive {
  color: #67c23a;
}

/* 底部链接样式 */
.project-links {
  text-align: center;
  margin-top: 40px;
  padding: 30px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  backdrop-filter: blur(5px);
}

.twitter-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.twitter-card .card-header {
  background: linear-gradient(90deg, #f8f9fa, #ffffff);
  border-bottom: 1px solid #f0f2f5;
}

.twitter-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.tweet-item {
  padding: 20px;
  border: 1px solid #f0f2f5;
  border-radius: 8px;
  margin-bottom: 15px;
  transition: all 0.3s ease;
  background: #fff;
  cursor: pointer;
  min-height: 250px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.tweet-item .tweet-text-expanded {
  max-height: 500px;
  overflow-y: auto;
}

.tweet-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.tweet-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.user-screen-name {
  font-size: 14px;
  color: #909399;
}

.tweet-text {
  font-size: 15px;
  line-height: 1.5;
  color: #303133;
  margin-bottom: 15px;
  white-space: pre-wrap;
  word-break: break-word;
  flex-grow: 1;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.tweet-text.tweet-text-expanded {
  -webkit-line-clamp: unset;
}

.tweet-expand {
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px 0;
  user-select: none;
  position: absolute;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  background: #fff;
  width: 80px;
  z-index: 1;
  border-radius: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.tweet-expand:hover {
  background: #f5f7fa;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}



.tweet-expand .el-icon {
  margin-left: 5px;
  transition: transform 0.3s ease;
}



.tweet-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 10px;
  flex-shrink: 0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #909399;
}

.tweet-date {
  font-size: 13px;
  color: #909399;
  margin-top: auto;
  padding-top: 10px;
  flex-shrink: 0;
  margin-bottom: 30px;
}

/* Twitter用户推荐样式 */
.twitter-users-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.twitter-users-card .card-header {
  background: linear-gradient(90deg, #f8f9fa, #ffffff);
  border-bottom: 1px solid #f0f2f5;
}

.user-item {
  padding: 20px;
  border: 1px solid #f0f2f5;
  border-radius: 8px;
  margin-bottom: 15px;
  transition: all 0.3s ease;
  background: #fff;
  text-align: center;
  cursor: pointer;
  min-height: 250px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.user-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.user-avatar-large {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.user-name-large {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
  margin-bottom: 5px;
}

.user-screen-name-large {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.user-followers {
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.project-links p {
  margin-bottom: 20px;
  color: #606266;
  font-size: 1.1rem;
}

.project-links-container {
  display: flex;
  justify-content: center;
  gap: 15px;
  flex-wrap: wrap;
}

/* 更新日志样式 */
.update-log {
  background: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

.update-log h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  color: #303133;
  font-size: 1.3rem;
}

.update-log ol {
  padding-left: 20px;
}

.update-log li {
  margin-bottom: 10px;
  line-height: 1.5;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .price-item {
    min-width: 33.33%;
  }

  .overview-card .overview-item {
    border-right: none;
    border-bottom: 1px solid #f0f2f5;
    padding: 15px 10px;
  }

  .overview-card .el-col {
    margin-bottom: 10px;
  }

  .stat-card {
    height: 120px;
  }
}

@media (max-width: 992px) {
  .stat-card {
    margin-bottom: 15px;
  }

  .el-col-4 {
    width: 50%;
  }

  .project-links-container {
    flex-direction: column;
    align-items: center;
  }

  .el-col-6 {
    width: 50%;
  }
}

@media (max-width: 768px) {
  .price-item {
    min-width: 50%;
  }

  .address-info {
    flex-direction: column;
    text-align: center;
  }

  .address-label, .address-value {
    margin: 5px 0;
  }

  .el-col-4 {
    width: 100%;
  }

  .el-col-12 {
    width: 100%;
    margin-bottom: 15px;
  }

  .overview-card .el-col {
    width: 100%;
    margin-bottom: 15px;
  }

  .el-col-6 {
    width: 100%;
    margin-bottom: 15px;
  }
}

@media (max-width: 480px) {
  .price-item {
    min-width: 100%;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-header .el-button {
    margin-top: 10px;
    align-self: flex-end;
  }

  .app-container {
    padding: 10px;
  }
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.el-row {
  animation: fadeIn 0.5s ease-out;
}

.el-row:nth-child(2) { animation-delay: 0.1s; }
.el-row:nth-child(3) { animation-delay: 0.2s; }
.el-row:nth-child(4) { animation-delay: 0.3s; }
.el-row:nth-child(5) { animation-delay: 0.4s; }
.el-row:nth-child(6) { animation-delay: 0.5s; }
.el-row:nth-child(7) { animation-delay: 0.6s; }
.el-row:nth-child(8) { animation-delay: 0.7s; }
.el-row:nth-child(9) { animation-delay: 0.8s; }
.el-row:nth-child(10) { animation-delay: 0.9s; }
</style>
